/**
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.easemob.chatuidemo.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;

import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMGroup;
import com.easemob.chat.EMGroupManager;
import com.easemob.chatuidemo.adapter.GroupAdapter;
import com.easemob.chatuidemo.adapter.GroupFragmentAdapter;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.PauseOnScrollListener;

import net.mihome.app.R;
import net.mihome.app.bean.Group;
import net.mihome.app.ui.GroupBean;
import net.mihome.app.ui.MainPager;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import me.maxwin.view.XListView;

/**
 * 联系人列表页
 * 
 */
public class LinliquanFragment extends Fragment {
    static LinliquanFragment instance;
    protected List<GroupBean> grouplist=new ArrayList<GroupBean>();
    private GroupFragmentAdapter groupAdapter;
	private ListView groupListView;
	private boolean hidden;
	private InputMethodManager inputMethodManager;
	private List<String> blackList;
    private ImageLoader imageLoader;
    private View serverStatusView;
    protected static final String STATE_PAUSE_ON_SCROLL = "STATE_PAUSE_ON_SCROLL";
    protected static final String STATE_PAUSE_ON_FLING = "STATE_PAUSE_ON_FLING";
    protected boolean pauseOnScroll = false;
    protected boolean pauseOnFling = true;
    public static LinliquanFragment newInstance(){
        if(instance==null){
            try{
                instance=new LinliquanFragment();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return instance;
    }
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_contact_list, container, false);
	}

    @Override
	public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
            if (savedInstanceState != null && savedInstanceState.getBoolean("isConflict", false))
                return;
            serverStatusView=getView().findViewById(R.id.unconnection_server);
            imageLoader=ImageLoader.getInstance();
            inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            groupListView = (ListView) getView().findViewById(R.id.list);
            groupListView.setOnScrollListener(new PauseOnScrollListener(imageLoader, pauseOnScroll, pauseOnFling));
            groupAdapter = new GroupFragmentAdapter(getActivity(), 1, grouplist,imageLoader);
            groupListView.setAdapter(groupAdapter);
            refresh();
            groupListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Object tag = view.getTag();
                    if ((tag instanceof Integer) && (((Integer) tag)).compareTo(GroupAdapter.VIEW_TYPE_MY_FRIENDS) == 0) {
                        //进入我的好友列表
                        startActivity(new Intent(getActivity(), ContactlistActivity.class));
                    } else if ((tag instanceof Integer) && (((Integer) tag)).compareTo(GroupAdapter.VIEW_TYPE_PUBLIC_GROUP) == 0) {
                        // 进入公开圈子列表页面
                        startActivity(new Intent(getActivity(), PublicGroupsActivity.class));
                    } else if ((tag instanceof Integer) && (((Integer) tag)).compareTo(GroupAdapter.VIEW_TYPE_NOTICE) == 0) {
                        // 进入申请和通知
                        startActivity(new Intent(getActivity(), NewFriendsMsgActivity.class));
                    } else if ((tag instanceof EMGroup)) {
                        //进入圈子扯蛋
                        EMGroup emGroup = (EMGroup) tag;
                        Intent intent = new Intent(getActivity(), ChatActivity.class);
                        // it is group chat
                        intent.putExtra("chatType", ChatActivity.CHATTYPE_GROUP);
                        intent.putExtra("groupId", emGroup.getGroupId());
                        startActivityForResult(intent, 0);
                    }
                }
            });
        registerForContextMenu(groupListView);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		// 长按前两个不弹menu
//		if (((AdapterContextMenuInfo) menuInfo).position > 2) {
//			getActivity().getMenuInflater().inflate(R.menu.context_contact_list, menu);
//		}
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		return super.onContextItemSelected(item);
	}


	@Override
	public void onSaveInstanceState(Bundle outState) {
	    if(((MainPager)getActivity()).isConflict)
	        outState.putBoolean("isConflict", true);
	    super.onSaveInstanceState(outState);
	    
	}

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        this.hidden = hidden;
        if (!hidden) {
            refresh();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!hidden) {
            refresh();
        }
    }
    // 刷新ui
    public void refresh() {
        List<EMGroup> list=EMGroupManager.getInstance().getAllGroups();
        grouplist.clear();
        if(list!=null){
            Iterator<EMGroup> iterator=list.iterator();
            while(iterator.hasNext()){
                EMGroup emGroup=iterator.next();
                EMConversation conversation = EMChatManager.getInstance().getConversation(emGroup.getGroupId());
                int unRead = conversation.getUnreadMsgCount();
                GroupBean groupBean=new GroupBean();
                groupBean.setEmGroup(emGroup);
                groupBean.setUnRead(unRead);
                if(unRead>0){
                    grouplist.add(0,groupBean);
                }else{
                    grouplist.add(groupBean);
                }
            }
        }
        groupAdapter.notifyDataSetChanged();
    }
    /**
     * 修改状态
     * */
    public void unconnect(){
       if(serverStatusView!=null){
           serverStatusView.setVisibility(View.VISIBLE);
       }
    }

    public void connected(){
        if(serverStatusView!=null){
            serverStatusView.setVisibility(View.GONE);
        }
    }
 }
